from django.shortcuts import render,HttpResponse
from .. models import GoodsClass
from django.core.urlresolvers import reverse
from django.http import JsonResponse

# Create your views here.


def gclass_add(request):
    data = GoodsClass.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
    if data:
        for i in data:
            numvar = i.path.count(',')-1
            print(numvar)
            i.name = numvar * '|----' + i.name
        context = {'data':data}
        return render(request,'myadmin/gclass/add.html',context)
    else:
        return render(request,'myadmin/gclass/add.html')
def gclass_insert(request):
    res = request.POST.dict()
    res.pop('csrfmiddlewaretoken')
    gcname = res['name']
    gcpid = res['gclass']
    if res['gclass'] == '0':
        gcpath = res['gclass']+','
    else:
        fob_path = GoodsClass.objects.get(id=gcpid).path
        gcpath = fob_path + res['gclass']+','
    ob = GoodsClass()
    ob.name = gcname
    ob.pid = gcpid
    ob.path = gcpath
    ob.save()
    return HttpResponse('<script>alert("添加成功");location.href="'+reverse('gclass_list')+'"</script>')

def gclass_list(request):
    data = GoodsClass.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
    # data = GoodsClass.objects.all()
    for i in data:
        numvar = i.path.count(',')-1
        i.sub = numvar * '|----'
        if i.pid != '0':
            ob_name = GoodsClass.objects.get(id=i.pid).name
            i.cname = ob_name
    context = {'data':data}
    return render(request,'myadmin/gclass/list.html',context)


# 删除功能
def gclass_del(request):
    uid = request.GET.get('uid')
    # 有子类不能删除
    res = GoodsClass.objects.filter(pid=uid).count()
    # 分类下有商品不能删除
    if res:
        data = {'msg':'当前类下有子类，不能删除','code':0}
        return JsonResponse(data)
    else:
        ob = GoodsClass.objects.filter(id=uid)
        ob.delete()
        data = {'msg':'删除成功','code':1}
        return JsonResponse(data)

def gclass_edit(request):
    res = request.GET.dict()
    ob = GoodsClass.objects.get(id=res['id'])
    ob.name = res['data']
    ob.save()
    data = {'msg':'修改成功'}
    return JsonResponse(data)
